<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
    <jsp:include page="inc/js.jsp"/>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>首页</title>
    <jsp:include page="inc/css.jsp"/>
    <script src="static/js/echarts.min.js"></script>
    <style>
        img {
            opacity: 0.5;
            filter: alpha(opacity=40); /* 针对 IE8 以及更早的版本 */
        }
    </style>
</head>
<body class="hold-transition sidebar-mini">
<div class="wrapper">
    <jsp:include page="inc/menu.jsp"/>
    <div class="content-wrapper">
        <div class="content-header" style="font-weight: bolder;text-align: center;">
            <h1>欢迎登陆${sessionScope.login_master_company_name}智能环境监测平台</h1>
        </div>

        <section class="content" style="padding-left: 15px;">
            <!-- 为ECharts准备一个具备大小（宽高）的Dom -->
            <div id="main1" style="width: 100%;"></div>

            <!-- 为ECharts准备一个具备大小（宽高）的Dom -->
            <div id="main2" style="width: 100%;"></div>
        </section>
    </div>
</div>

</body>
</html>

<script type="application/javascript">
    let angleCount = 10;   // 设置X轴文字的倾斜角度
    let marginCount = 20;  // 设置刻度标签与轴线之间的距离
    let newLineCount = 10; // 设置X轴每行文字显示的最大数量，超过即换行显示
    let baseBarWidth = 30;// 设置X轴柱状图宽度
    let currentSelectedIndex = 1;

    $(function () {
        let baseHeight = window.innerHeight;
        let baseWidth = window.innerWidth;
        baseBarWidth = (baseWidth * 0.5) / 10;

        $('#main1').css('height', baseHeight / 2 - 70 + "px");
        $('#main2').css('height', baseHeight / 2 - 70 + "px");

        loadAlarmMessageStatic(10);
        loadCompanyBalanceStatic(10);

        window.onload = function () {
            checkSelectMenu('baseLi');

            loadMenuColor('baseLi');
        }
    });

    function loadAlarmMessageStatic(count) {
        // 基于准备好的dom，初始化echarts实例
        let myChart1 = echarts.init(document.getElementById('main1'));

        startLoading();

        $.post('backend/alarmMessage/alarmMessageStatic', {
            count: count
        }, function (result) {
            endLoading();

            const names = [];
            const values = [];

            if (result.code === 0 && result.data.length > 0) {
                $.each(result.data, function (i, item) {
                    names.push(item.name);
                    values.push(item.count);
                });

                // 指定图表的配置项和数据
                let option1 = {
                    title: {
                        text: '今日设备预警数量统计',
                        left: 'center', // 标题居中
                        top: 'top', // title组件离容器上侧的距离
                        textStyle: {
                            color: '#53868B',// 文字颜色
                            fontStyle: 'normal', // 字体风格，可选 'normal', 'italic', 'oblique'
                            fontWeight: 'normal',// 字体粗细，可选 'normal', 'bold', 'bolder', 'lighter', 100 | 200 | 300 | 400
                            fontFamily: 'sans-serif',// 字体系列
                            fontSize: 18// 字体大小
                        }
                    },
                    tooltip: {},
                    legend: {
                        orient: 'vertical', // 图例的排列方向
                        x: 'right', // 图例在右侧
                        padding: [0, 50, 0, 0], // 图例的内边距
                        data: ['预警数量']
                    },
                    grid: {
                        left: '10%',
                        bottom: '20%'
                    },
                    xAxis: {
                        data: names,
                        axisLabel: {
                            interval: 0,
                            rotate: angleCount,
                            margin: marginCount,
                            formatter: function (params) {
                                let newParamsName = "";
                                let paramsNameNumber = params.length;
                                let rowNumber = Math.ceil(paramsNameNumber / newLineCount);
                                if (paramsNameNumber > newLineCount) {
                                    for (let p = 0; p < rowNumber; p++) {
                                        let tempStr = "";
                                        let start = p * newLineCount;
                                        let end = start + newLineCount;
                                        if (p === rowNumber - 1) {
                                            tempStr = params.substring(start, paramsNameNumber);
                                        } else {
                                            tempStr = params.substring(start, end) + "\n";
                                        }
                                        newParamsName += tempStr;
                                    }
                                } else {
                                    newParamsName = params;
                                }
                                return newParamsName;
                            }
                        }
                    },
                    yAxis: {},
                    series: [{
                        name: '预警数量',
                        type: 'bar',
                        barWidth: baseBarWidth,
                        itemStyle: {
                            normal: {
                                color: function (d) {
                                    return "#66CC00";
                                }
                            },
                        },
                        data: values
                    }]
                };

                // 使用刚指定的配置项和数据显示图表。
                myChart1.setOption(option1);

                // 响应式调整
                window.addEventListener('resize', function () {
                    myChart1.resize();
                });
            }
        });
    }

    function loadCompanyBalanceStatic(count) {
        // 基于准备好的dom，初始化echarts实例
        let myChart2 = echarts.init(document.getElementById('main2'));

        startLoading();

        $.post('backend/balance/companyBalanceStatic', {
            company: 1, type: 1
        }, function (result) {
            endLoading();

            const names = [];
            const totalUsedValues = [];
            const totalUnusedValues = [];

            if (result.code === 0 && result.data.length > 0) {
                $.each(result.data, function (i, item) {
                    names.push(item.codeDictName);
                    totalUsedValues.push((item.totalUsedCount / 1000).toFixed(2));
                    totalUnusedValues.push((item.totalUnusedCount / 1000).toFixed(2));
                });

                // 图表配置
                const option = {
                    tooltip: {
                        trigger: 'axis', axisPointer: {type: 'shadow'}, backgroundColor: 'rgba(0,0,0,0.7)',  // 添加背景色
                        borderWidth: 0,                      // 去除边框
                        padding: 10,                         // 增加内边距
                        textStyle: {
                            color: '#FFF', fontSize: 12
                        }, formatter: function (params) {
                            // 正确获取值并转为数值类型
                            const used = Number(params[0].value);    // 已使用量（系列0）
                            const unused = Number(params[1].value);   // 未使用量（系列1）
                            const category = params[0].name;

                            // 计算总量和使用率（防止除0错误）
                            const total = used + unused;
                            const rate = total > 0 ? Math.min(Math.round((used / total) * 100), 100) : 0;

                            // 格式化工件内容
                            return '<div style="font-weight:bold;">' + category + '</div><div><span style="display:inline-block;width:10px;height:10px;background:#66CC00;"></span>未使用: ' + unused.toLocaleString() + 'T</div><div style="margin-top:5px;"><span style="display:inline-block;width:10px;height:10px;background:#FF3333;"></span>已使用: ' + used.toLocaleString() + 'T</div><div style="margin-top:5px;border-top:1px solid #555;padding-top:5px;">使用率: <span style="color:#FFD700;font-weight:bold;">' + rate + '%</span></div><div>总量: <b>' + total.toLocaleString() + '</b>T</div>';
                        }, // 关键设置：手动控制tooltip显示
                        show: true, alwaysShowContent: false, triggerOn: 'click', hideDelay: 0
                    }, legend: {
                        data: ['已使用量', '剩余使用量'], textStyle: {
                            color: '#808080'
                        }, right: 20, top: 10, itemWidth: 16, itemHeight: 8
                    }, grid: {
                        left: '3%', right: '4%', bottom: '10%', top: '15%', containLabel: true
                    }, xAxis: {
                        type: 'category', data: names, axisLine: {lineStyle: {color: '#ccc'}}, axisLabel: {color: '#666', fontSize: 12}, axisTick: {show: false}
                    }, yAxis: {
                        type: 'value', name: '吨(T)', nameTextStyle: {color: '#666', fontSize: 12}, axisLine: {show: false}, axisLabel: {color: '#666', fontSize: 12}, splitLine: {lineStyle: {color: 'rgba(0,0,0,0.05)'}}
                    }, series: [{
                        name: '已使用量', type: 'bar', stack: 'stack1', data: totalUsedValues, barWidth: '35%', itemStyle: {
                            color: '#FF3333', borderRadius: [0, 0, 6, 6]
                        }, label: {
                            show: false, position: 'top', formatter: '{c}', color: '#FF3333', fontWeight: 'bold', fontSize: 12
                        }, emphasis: {
                            itemStyle: {
                                shadowColor: 'rgba(0, 0, 0, 0.3)', shadowBlur: 10
                            }
                        }
                    }, {
                        name: '剩余使用量', type: 'bar', stack: 'stack1', data: totalUnusedValues, barWidth: '35%', itemStyle: {
                            color: '#66CC00', borderRadius: [6, 6, 0, 0]
                        }, label: {
                            show: false, position: 'insideTop', formatter: '{c}', color: '#333', fontWeight: 'bold', fontSize: 12
                        }, emphasis: {
                            itemStyle: {
                                shadowColor: 'rgba(0, 0, 0, 0.3)', shadowBlur: 10
                            }
                        }
                    }], animation: true, animationDuration: 800, animationEasing: 'cubicOut'
                };

                // 使用刚指定的配置项和数据显示图表。
                myChart2.setOption(option);

                // 关键：实现点击柱子持续显示tooltip
                myChart2.on('click', function (params) {
                    // 如果点击的是柱子
                    if (params.componentType === 'series' && params.seriesType === 'bar') {
                        _alarmRuleList.v.currentSelectedIndex = params.dataIndex;

                        // 显示tooltip
                        myChart2.dispatchAction({
                            type: 'showTip', seriesIndex: 0, dataIndex: _alarmRuleList.v.currentSelectedIndex
                        });
                    }
                });

                // 点击空白区域隐藏tooltip
                myChart2.getZr().on('click', function (event) {
                    // 如果没有点击到图形元素
                    if (!event.target) {
                        _alarmRuleList.v.currentSelectedIndex = null;
                        myChart2.dispatchAction({
                            type: 'hideTip'
                        });
                    }
                });

                // 响应窗口大小变化
                window.addEventListener('resize', function () {
                    myChart2.resize();
                });
            }
        });
    }
</script>